package com.likou;

import java.util.HashMap;
import java.util.Map;

/**
 * Author: 陈桂明
 * Date: 2025/9/10 10:55
 * Description: q105
 */
public class q105 {

    Map<Integer, Integer> map = new HashMap<>();

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int size = inorder.length;

        for (int i = 0; i < size; i++) {
            map.put(inorder[i], i);
        }

        return insert(preorder, inorder, 0, size - 1, 0, size - 1);

    }

    private TreeNode insert(int[] preorder, int[] inorder, int pl, int pr, int il, int ir) {
        if (pl > pr || il > ir) {
            return null;
        }

        TreeNode root = new TreeNode(preorder[pl]);
        Integer w = map.get(preorder[pl]);
        int n = w - il;
        root.left = insert(preorder, inorder, pl + 1, pl + n, il, w - 1);
        root.right = insert(preorder, inorder, pl + n + 1, pr, w + 1, ir);

        return root;
    }
}
